import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ValidateProvider} from "../../providers/validate/validate";
import {ConfigProvider} from "../../providers/config/config";
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {UtilsProvider} from "../../providers/utils/utils";

@IonicPage({
    segment: 'member/bond/recharge',
    defaultHistory: ['PersonBondPage']
})
@Component({
    selector: 'page-bond-recharge',
    templateUrl: 'bond-recharge.html',
})
export class BondRechargePage {
    token: any;
    rechargeData = {
        frozen_money: ''
    };
    surplus: any;
    frozen_money:number;
    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public validate: ValidateProvider,
        public config: ConfigProvider,
        public httpService: HttpServicesProvider,
        public util: UtilsProvider
    ) {
    }

    ionViewCanEnter() {
        return this.validate.checkLogin();
    }

    ionViewWillEnter() {
        if (!this.validate.checkLogin()) {//登录
            this.navCtrl.push('LoginPage', {'backPage': 'MemberPage'});
        } else {
            this.token = this.config.getToken();
            this.getSurplus();
            this.getFrozenMoney();
        }
    }

    /**
     * 获取用户当前保证金金额
     * */
    getFrozenMoney() {
        this.httpService.requestPostData('/echarge/residue_recharge_frozen', {token: this.token}, response => {
            if(response['error'] == 200){
                let data = response['data'];
                this.frozen_money = data['frozen_money'];
            }else{
                this.util.presentAlert('系统有误，请稍后再试');
                this.navCtrl.pop();
            }

        });
    }

    // 获取用户余额
    getSurplus() {
        this.httpService.requestData('/echarge/index/token/' + this.token, response => {
            this.surplus = response['money'];
        });
    }

    showNotice = false;

    // 验证余额是否足够
    checkMoney() {
        this.showNotice = this.rechargeData.frozen_money > this.surplus;
    }

    doRecharge() {
        if (parseFloat(this.rechargeData.frozen_money) < 1) {
            this.util.presentAlert('最小充值金额不少于1元')
            return false;
        }
        if (this.showNotice) {
            this.util.presentAlert('余额不足');
            return false;
        }
        ///echarge/recharge_frozen
        this.httpService.requestPostData('/echarge/recharge_frozen/token/' + this.token, this.rechargeData, response => {
            if (response['error'] == 200) {
                this.navCtrl.push('BondRechargeResultPage');
            } else {

            }
        });
    }

}
